# -*- coding: utf-8 -*-
# @Time    : 2017/5/10

from sympy import solveset
from mathsolver.functions.base import BaseSymbolValue, BaseFunction
from mathsolver.functions.daoshu.jizhi import HanShuJiZhi
from mathsolver.functions.hanshu.helper import check_func


class JiDaZhiQiuCan(BaseFunction):
    """已知函数极大/小值求参数"""
    jizhi = "极大值"

    def solver(self, *args):
        func, number = check_func(args[0]), args[1].sympify()

        # 计算极值点
        jizhi_solver = HanShuJiZhi(self.known).solver(func)
        self.steps.extend(jizhi_solver.steps)
        if self.jizhi == "极大值":
            jizhidian = jizhi_solver.jidazhidian
        elif self.jizhi == "极小值":
            jizhidian = jizhi_solver.jixiaozhidian
        else:
            jizhidian = jizhi_solver.jizhidian

        # 极值点和题目给定极值点相等
        result = set()
        if isinstance(jizhidian, list):
            for jizhi_x, jizhi_y in jizhidian:
                result = result.union(solveset(jizhi_y - number))
        else:
            for canshu_range, jizhis in jizhidian.items():
                for jizhi_x, jizhi_y in jizhis:
                    result = result.union(solveset(jizhi_y - number, domain=canshu_range))

        output_result = BaseSymbolValue({jizhi_solver.canshu: list(result)})
        self.steps.append(["", "解得：%s" % output_result.printing()])
        self.output.append(output_result)
        self.label.add("已知函数极值求参数")
        return self


class JiXiaoZhiQiuCan(JiDaZhiQiuCan):
    jizhi = "极小值"


class JiZhiQiuCan(JiDaZhiQiuCan):
    jizhi = "极值"


if __name__ == '__main__':
    pass
